import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:gameplay_flutter/lib_basemodel/country/country_model.dart';
import 'package:gameplay_flutter/lib_baseview/lib_baseview.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_state_manager/src/simple/get_state.dart';
import 'package:get_storage/get_storage.dart';
import 'package:ones/ui.dart';
import 'package:provider/provider.dart';
import '../../../generated/assets.dart';
import '../../../lib_baseview/theme/jr.dart';
import '../../../lib_baseview/widget/empty_view/jr_empty_view.dart';
import '../../../m_login/select_country/select_country_model.dart';
import '../../../resource/language/generated/l10n.dart';
import '../compoents/fresh_components.dart';
import '../home_controller.dart';
import 'home_countries_controller.dart';


class HomeCountriesPage extends StatefulWidget {
  final String country;
  HomeCountriesPage({Key? key, required this.country,}){
    Get.put(HomeCountriesController());
  }

  @override
  State<HomeCountriesPage> createState() => _HomeCountriesPage();
}

class _HomeCountriesPage extends State<HomeCountriesPage> with SingleTickerProviderStateMixin {
  final EasyRefreshController _refreshControllerRoom = EasyRefreshController();
  late HomeCountriesController _countriesController;
  bool hasMore = false;
  String queryType = "";
  String value = "1";
  bool isOpen = false;
  late List<CountryModel> countries = [];
  late int selectIndex = 0;
  OverlayEntry? _overlayEntry;
  bool noMoreState = false;
  int pageNum = 1;

  selectChange(value) {
    print("值改变了：$value");
  }

  @override
  void initState() {
    super.initState();
    _countriesController = Get.find<HomeCountriesController>();
    _countriesController.loadData(widget.country,'refresh',1);
    countries = _countriesController.countries.value;
    if(countries.length > 0){
      selectIndex =  countries.indexWhere((v) => v.country == widget.country);
      jumpToView(selectIndex);
    }
  }

  @override
  void dispose() {
    if(isOpen){
      hideOverlay();
    }
    super.dispose();
  }

  void jumpToView(index){
    Future.delayed(const Duration(seconds: 1), () {
      final key = GlobalObjectKey(index);
      final context = key.currentContext;
      if (context != null) {
        Scrollable.ensureVisible(
          context,
          duration: const Duration(milliseconds: 500),
          curve: Curves.easeOut,
        );
      }
    });
  }


  Future<void> _onRefreshPopularRoom() async {
    // _refreshControllerMarket.finishRefresh(success: true);
    _countriesController.loadData(countries[selectIndex].country.toString(),'refresh',1);
    setState(() {
      noMoreState = false;
      pageNum = 1;
    });
    _refreshControllerRoom.finishLoad(noMore: false);
  }

  Future<void> _onLoadRoom() async {
    if(_countriesController.recommend.value.length == 0){
      setState(() {
        noMoreState = true;
      });
    } else {
      if(!noMoreState){
        setState(() {
          pageNum++;
          hasMore = true;
        });
        print({ pageNum++,999999990});
        var status =  await _countriesController.loadData(countries[selectIndex].country.toString(),'more', pageNum++);
        if(!status){
          setState(() {
            hasMore = false;
          });
          _refreshControllerRoom.finishLoad(noMore: true);
        }
      } else {
        setState(() {
          noMoreState = false;
        });
        Future.delayed(Duration(milliseconds: 1000), () {
          setState(() {
            noMoreState = true;
          });
        });
      }
    }


    // _refreshControllerMarket.finishRefresh(success: true);
  }

  Widget listWidget(context, model, filteredList) {
    if (model.countryList.isEmpty) {
      return JREmptyView(
        desc: T.current.go_to_get_your_car,
      );
    }
    return ConstrainedBox(
        constraints: BoxConstraints(
          maxHeight: 150,
        ),
        child: ListView.builder(
            scrollDirection: Axis.vertical,
            itemCount: filteredList.length,
            itemBuilder: (context,index){
              return getItem(filteredList[index], index);
            }
        )
    );
  }

  Widget getItem(item, index) {
    return InkWell(
      onTap: () {
        setState(() {
          selectIndex = index;
          isOpen = !isOpen;
        });
        hideOverlay();
        _countriesController.loadData(countries[index].country.toString(),'refresh',1);
        jumpToView(index);

      },
      child: Container(
        margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),
        padding: const EdgeInsets.fromLTRB(30, 8, 30, 8),
        decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(8)),
            color: selectIndex == index ? const Color(0xffE5DFFF) : const Color(0xffF4F3F6)
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Image.network(
                  item.flag,
                  width: 42.w,
                  height: 30.h,
                  fit: BoxFit.fill,
                ),
                const SizedBox(width: 20,),
                Text(item.country ?? '').color(
                    selectIndex == index ? const Color(0xff444444) : const Color(
                        0xffA8A8A8)).fontSize(16),
                const SizedBox(width: 20,),
              ],
            ),
            selectIndex == index
                ? const Icon(
              Icons.check_circle_outline, color: Color(0xff8A72FE), size: 28,)
                : Container()
          ],
        ).center(),
      ),
    );
  }

  Widget _popularList() {
    return  EasyRefresh(
        onRefresh: _onRefreshPopularRoom,
        onLoad: _onLoadRoom,
        header: buildCustomHeader,
        footer: buildCustomFooter,
        controller: _refreshControllerRoom,
        child:_countriesController.recommend.value.isNotEmpty? MasonryGridView.count(
          crossAxisCount: 1,
          mainAxisSpacing: 6,
          crossAxisSpacing: 4,
          itemCount: _countriesController.recommend.value.length,
          itemBuilder: (context, index) {
            var newColors = 0;
            var newBgColors = 0;
            var roomItem;
            try{
              roomItem  =  _countriesController.recommend.value[index];
              if(roomItem.roomCategoryColor != null){
                String color = '0xff' + roomItem.roomCategoryColor.split('#')[1];
                newColors = color.toInt();
              } else {
                newColors = 0xffc1c1c1;
              }
              if(roomItem.backgroundUrl != null){
                String bgColor = '0xff' + roomItem.backgroundUrl.split('#')[1];
                newBgColors = bgColor.toInt();
              } else {
                newBgColors = 0xffc1c1c1;
              }
            }catch(e){
              return Container();
            }
            return Column(
              children: [
                Row(
                  children: [
                    // Image.asset(roomItem.roomIcon,width: 100,height: 100,),
                    Container(
                      width: 72,
                      height: 72,
                      margin: const EdgeInsets.only(left: 5),
                      decoration: ShapeDecoration(
                          image:DecorationImage(
                            // image:index % 2 == 0 ? AssetImage(Assets.homeAvatar1) : AssetImage(Assets.homeAvatar2),
                              image: NetworkImage(roomItem.roomIcon?? ''),
                              fit: BoxFit.fitWidth
                          ),
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadiusDirectional.circular(8))
                      ),

                      // BoxDecoration(
                      //     borderRadius: BorderRadius.all(Radius.circular(10))
                      // ),
                      // child:  Image.asset(index % 2 == 0?Assets.homeAvatar1 : Assets.homeAvatar2,fit: BoxFit.fitWidth,),
                    ),
                    const SizedBox(width: 5,),
                    Expanded(child: SizedBox(
                      height:87,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Image.asset(Assets.homeCountries,width: 30,height: 20,),
                                  const SizedBox(width: 3,),
                                  SizedBox(
                                    width: 180,
                                    child: Text(
                                      roomItem.roomName,
                                      softWrap: false,
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ).fontSize(16),
                                  )
                                ],
                              ),
                              Text(
                                roomItem.slogan,
                                softWrap: false,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ).fontSize(12).color(Color(0xffC1C1C1)),
                            ],
                          ),
                          Row(
                            children: [
                              roomItem.categoryTypeIcon != null?Image.network(roomItem.categoryTypeIcon,width: 24,):Image(image:AssetImage(Assets.homeIcRoomLove),width: 24,),
                              const SizedBox(width: 4,),
                              Container(
                                padding: EdgeInsets.fromLTRB(8, 1, 8, 1),
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(Radius.circular(10)),
                                    color: Color(newBgColors)
                                ),
                                child: Text(roomItem.roomCategoryName).fontSize(10).colorInt(newColors),
                              ),
                              const Spacer(),
                              const Image(image: AssetImage(Assets.homeIcFire,),width: 12,height: 12,),
                              const SizedBox(width: 5,),
                              Text(roomItem.scoreWeight.toString()).fontSize(12).colorInt(0xffC1C1C1),
                            ],
                          ).marginBottom(5),
                        ],
                      ),
                    ).marginLeft(10).paddingRight(8.0),)
                  ],
                ).roundedRect(8).paddingAll(5).colorBg(bgColor: Colors.white).onClick(() {
                  _countriesController.joinRoomPage(context,roomItem);
                }),
              ],
            );
          },
        ) : Center(
          child: Image.asset(Assets.noData,fit: BoxFit.fill,),
        )
    );
  }

  Widget _countriesList(BuildContext context) {
    return SizedBox(
      height: 65,
      child:  SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            children:List.generate(countries.length, (index) =>
                Container(
                  key: GlobalObjectKey(index),
                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                  child: Column(
                    children: [
                      Text(countries[index].country!)
                          .fontSize(16)
                          .color(selectIndex == index?const Color(0xff8A72FE):const Color(0xffC1C1C1))
                          .fontWeight(selectIndex == index?FontWeight.bold:null),
                      countries[selectIndex] == countries[index]? const Image(image:AssetImage(Assets.homeTabBottom),width: 18,):SizedBox(height: 10,)
                    ],
                  ),
                ).onTap((){
                  setState(() {
                    selectIndex = index;
                  });
                  _countriesController.loadData(countries[index].country.toString(),'refresh',1);
                  // _scrollController
                  //     .jumpTo(_scrollController.position.maxScrollExtent);
                })
            )
          ),
      )

      // ListView.builder(
      //     scrollDirection: Axis.horizontal,
      //     controller: _scrollController,
      //     itemCount: countries.length,
      //     itemBuilder: (context,index){
      //       return
      //     }
      // ),
    );
  }

  void showOverlay() {
    final entry = OverlayEntry(
        builder: (context) =>AnimatedContainer(
            duration: const Duration(milliseconds: 500),
            curve: Curves.easeInOut,
            height: !isOpen ? 200.0 : 0.0,
            width: double.infinity,
            transform: Matrix4.translationValues(0, 118.h, 0),
            child:  Container(
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(.1)
              ),
              child: Stack(
                children: [
                  Positioned(
                      child: Column(
                        children: [
                          Container(
                            padding: const EdgeInsets.only(bottom: 20),
                            decoration: const BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20),bottomRight: Radius.circular(20))
                            ),
                            height: MediaQuery.sizeOf(context).height - 320,
                            child: ChangeNotifierProvider(
                                create: (_) => SelectCountryModel(),
                                child: Consumer<SelectCountryModel>(
                                  builder: (context, model, _) {
                                    final filteredList = model.countryList;
                                    return listWidget(
                                        context, model, filteredList
                                    );
                                  },
                                )
                            ),
                          ),
                          InkWell(
                            onTap: (){
                              hideOverlay();
                              setState(() {
                                isOpen = !isOpen;
                              });
                            },
                            child:  Container(
                                width: MediaQuery.sizeOf(context).width,
                                height: 280,
                                color: Colors.transparent,
                            ),
                          ),
                        ],
                      )
                  )
                ],
              ),
            )
        ),
    );
    Overlay.of(context).insert(entry);
    setState(() {
      _overlayEntry = entry;
    });
  }

  void hideOverlay() {
    _overlayEntry?.remove();
  }


  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeCountriesController>(builder: (controller) {
      return Scaffold(
        appBar: AppBar(
          title: Text(T.current.h1_countries),
          centerTitle: true,// 标题
          leading: IconButton( // 自定义返回按钮
            icon: const Icon(Icons.arrow_back_ios_new,size: 24,),
            onPressed: (){
              Navigator.pop(context);
              if(isOpen){
                hideOverlay();
              }
            },
          ),
          backgroundColor: const Color(0xffDCD4FF),
        ),
        backgroundColor: const Color(0xffFAFAFA),
        body: Column(
          children: [
            SafeArea(
              child: Container(
                decoration: BoxDecoration(
                  color:isOpen? Colors.white : Colors.transparent
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Expanded(
                        child: isOpen? Container(
                          height: 55,
                          padding: const EdgeInsets.only(left: 15,top: 10),
                          child: Text(T.current.h3_countries).fontSize(18),
                        )  : _countriesList(context)
                      // child: Text('12312311'),
                    ),
                    InkWell(
                      onTap: (){
                        if (isOpen) {
                          hideOverlay();
                        } else {
                          showOverlay();
                        }
                        setState(() {
                          isOpen = !isOpen;
                        });
                      },
                      child: Container(
                        transform: Matrix4.translationValues(0, -5, 0),
                        padding: EdgeInsets.symmetric(horizontal: 15,vertical: 10),
                        child: isOpen ? const Image(image: AssetImage(Assets.homeUp),width: 30,height: 12,)
                            : Image(image: AssetImage(Assets.homeDown),width: 30,height: 12,),
                      ),
                    ),
                  ],
                ),
              )
            ),
            const SizedBox(height: 5,),
            Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  transform: Matrix4.translationValues(0, -20, 0),
                  child: _popularList(),
                ),
            )
          ],
        ),
      );
    });
  }

}
